/*
 * Copyright 2009-2010 Belmont Software Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.belmont.backup;

import java.util.*;

public class BufferPool {
    static BufferPool instance = new BufferPool();
    static final int MAX_SIZE = 20;

    Hashtable<String,Vector<byte[]>> pools = new Hashtable<String, Vector<byte[]>>();

    public static BufferPool getInstance() {
	return instance;
    }

    public synchronized byte[] get(int size) {
	String k = Integer.toString(size);
	Vector<byte[]> pool = pools.get(k);

	if (pool == null || pool.size() == 0) {
	    return new byte[size];
	} else {
	    byte b[] = pool.elementAt(0);
	    pool.removeElementAt(0);
	    return b;
	}
    }

    public synchronized void put(byte b[]) {
	if (b == null) {
	    return;
	}
	String k = Integer.toString(b.length);
	Vector<byte[]> pool = pools.get(k);

	if (pool == null) {
	    pool = new Vector<byte[]>();
	    pools.put(k, pool);
	} else if (pool.size() == MAX_SIZE) {
	    return;
	}

	pool.addElement(b);
    }
}
	